package org.ssssssss.curd.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * className: SpringUtil<br>
 * description: Spring工具类<br>
 * createDate: 2020年1月7日<br>
 * 
 * @author chenzhuobin<br>
 * @version v1.0
 *
 */
@Component
public class MagicApiCurdSpringUtil implements BeanFactoryPostProcessor {

    /**
     * spring的容器上下文
     */
    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public synchronized void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        MagicApiCurdSpringUtil.beanFactory = beanFactory;
    }

    /**
     * 通过bean名称获取bean
     * 
     * @param beanName bean名称
     * @return bean对象
     */
    public static  <T> T  getBean(String beanName) {
        return (T) beanFactory.getBean(beanName);
    }

    /**
     * 通过bean类型获取bean
     * 
     * @param requiredType bean类型
     * @return  bean对象
     */
    public static   <T> T  getBean(Class<T> requiredType) {
        return beanFactory.getBean(requiredType);
    }

    /**
     * 通过bean名称及类型获取bean
     * 
     * @param beanName bean名称
     * @param requiredType bean类型
     * @return bean对象
     */
    public static   <T> T  getBean(String beanName, Class<T> requiredType) {
        return beanFactory.getBean(beanName, requiredType);
    }

    /**
     * 通过 bean类型 及 构造函数参数值 获取 Bean对象
     * @param requiredType bean类型
     * @param args 构造函数参数
     * @param <T> Bean类型
     * @return bean对象
     */
    public static <T> T getBean(Class<T> requiredType,Object... args){
        return beanFactory.getBean(requiredType,args);
    }


}
